package jpf.nextsearch.base;

import jpf.nextsearch.ds.dao.ConfigurationEntryDao;
import jpf.nextsearch.ds.model.ConfigurationEntryVO;

/**
 * 
 * @author <a href="mailto:jacek.pruszkowski@gmail.com">Jacek Pruszkowski</a>
 */
public class GlobalConfiguration extends GenericObject {
	private ConfigurationEntryDao configurationEntryDao;

	public void setConfigurationValue(String key, Object value) {
		ConfigurationEntryVO entry = getConfigurationEntry(key);

		if (entry == null) {
			entry = new ConfigurationEntryVO();
		}

		entry.setKey(key);
		entry.setValue(value.toString());

		getConfigurationEntryDao().saveOrUpdate(entry);
	}

	private ConfigurationEntryVO getConfigurationEntry(String key) {
		return getConfigurationEntryDao().get(key);
	}

	public String getConfigurationValue(String key) {
		ConfigurationEntryVO entry = getConfigurationEntry(key);

		if (entry == null) {
			return null;
		}
		return entry.getValue();
	}

	public Boolean getConfigurationValueBoolean(String key) {
		String val = getConfigurationValue(key);
		try {
			return Boolean.parseBoolean(val);
		} catch (Exception e) {
			if (isLoggingError()) {
				getLogger().error(
						"Invalid Boolean config value entry: " + val
								+ " for key: " + key, e);
			}
			return null;
		}

	}

	public Integer getConfigurationValueInteger(String key) {
		String val = getConfigurationValue(key);
		try {
			return Integer.parseInt(val);
		} catch (Exception e) {
			if (isLoggingError()) {
				getLogger().error(
						"Invalid Integer config value entry: " + val
								+ " for key: " + key, e);
			}
			return null;
		}
	}

	public Double getConfigurationValueDouble(String key) {
		String val = getConfigurationValue(key);
		try {
			return Double.parseDouble(val);
		} catch (Exception e) {
			if (isLoggingError()) {
				getLogger().error(
						"Invalid Double config value entry: " + val
								+ " for key: " + key, e);
			}
			return null;
		}
	}

	public void setConfigurationEntryDao(
			ConfigurationEntryDao configurationEntryDao) {
		this.configurationEntryDao = configurationEntryDao;
	}

	public ConfigurationEntryDao getConfigurationEntryDao() {
		return configurationEntryDao;
	}

}
